<script setup lang='ts'>
import { UpdateUserInfoService } from '@/api/User/user'
import type { IUser_Info } from '@/api/User/type'
import type { UploadProps } from 'element-plus'
import { isEqualObj } from '@/utils/isEqualObj'
import { IMAGE_URL } from '@/utils/request'
import bus from '@/utils/bus'

const emits = defineEmits(['handleClose'])
const formRef = ref()
const oldInfo = ref<IUser_Info>()
const formModel = ref<IUser_Info>({
  username: '',
  avatar: '',
  signature: '',
})

const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
  ],
  signature: [
    { required: true, message: '请输入个性签名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
  ],
})

const imageUrl = ref('')
const loading = ref(false)
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  loading.value = true
  if (
    rawFile.type !== 'image/jpeg' &&
    rawFile.type !== 'image/png' &&
    rawFile.type !== 'image/gif'
  ) {
    ElMessage.error('上传文件格式错误，请上传jpg/png/gif格式的图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 4) {
    ElMessage.error('上传文件大小不能超过4MB')
    return false
  }
  return true
}
const handleAvatarChange = (file: any) => {
  if(imageUrl.value){
    return;
  }
  imageUrl.value = URL.createObjectURL(file.raw)
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  if (response.code !== 200) {
    ElMessage.error('上传失败，请稍后重试')
    close()
    return
  }
  console.log('上传成功：', response, uploadFile)
  // 将上传成功返回的图片地址赋值给表单的logoUrl
  formModel.value.avatar = response.data
  imageUrl.value = response.data
  // 上传成功后，清楚校验信息
  formRef.value.clearValidate('avatar')
  loading.value = false
}
const handleAvatarError: UploadProps['onError'] = (
  error: any,
  uploadFile: any,
  uploadFiles: any
) => {
  console.log('上传失败：', error, uploadFile, uploadFiles)
  ElMessage.error('图片上传失败，请稍后重试')
  close()
}
// 表单是否变化
const isChanged = () => {
  if (isEqualObj(oldInfo.value, formModel.value)) {
    // ElMessage.warning('没有修改任何信息')
    close()
    return false
  }
  return true
}
// 提交
const handleUpdate = async () => {
  await formRef.value.validate()
  if (!isChanged()) return
  loading.value = true
  try {
    await UpdateUserInfoService(formModel.value)
    bus.emit('baseChange')
    // ElMessage.success('修改成功')
    emits('handleClose')
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}
// 关闭
const close = () => {
  imageUrl.value = ''
  loading.value = false
  formRef.value.resetFields()
  formModel.value = {
    username: '',
    avatar: '',
    signature: '',
  }
}
// 打开
const open = (data: any) => {
  console.log(data)
  oldInfo.value = { ...data }
  formModel.value = { ...data }
  imageUrl.value = data.avatar
}
defineExpose({
  open,
  close,
})
</script>
<template>
  <div class="basic-setting">
    <el-form :model="formModel" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="头像" prop="avatar">
        <el-upload
          :name="'avatar'"
          class="avatar-uploader"
          action="/api/apis/upload"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-change="handleAvatarChange"
          :on-error="handleAvatarError"
          :on-success="handleAvatarSuccess"
          accept="image/*"
        >
          <img v-if="imageUrl" :src="IMAGE_URL + imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formModel.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="个性签名" prop="signature">
        <el-input
          v-model="formModel.signature"
          :rows="2"
          maxlength="50"
          show-word-limit
          type="textarea"
          placeholder="请输入个性签名"
          class="signature-input"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleUpdate" :loading="loading">保存</el-button>
        <el-button @click="emits('handleClose')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style scoped lang='scss'>
.basic-setting {
  .signature-input {
    width: 100%;
    max-height: 100px;
    resize: none;
    cursor: none;
  }
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>